package com.ruoyi.basics.service.impl;



import com.ruoyi.basics.domain.User;
import com.ruoyi.basics.dto.HouseholdRegisterDto;
import com.ruoyi.basics.dto.SmsCodeDto;
import com.ruoyi.basics.mapper.UserMapper;
import com.ruoyi.basics.service.IVerifyCodeService;


import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void sendSmsCode(SmsCodeDto smsCodeDto) {
        String phone = smsCodeDto.getPhone();
        // 判断手机号码是否为空
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("手机号不能为空");
        }
        // 判断手机号码是否注册过
        User user = userMapper.selectUserByPhone(phone);
        if (user != null) {
            throw new BusinessException("改手机号已被注册,请直接登录");
        }
        Object codeObj = redisTemplate.opsForValue().get("register" + phone);
        String smsCode = null;
        if (codeObj == null) {
            //如果第一次发送，redis里面没有验证码，就随机生成一个六位数的手机验证码
            smsCode = StrUtils.getRandomString(6);
        } else {
            //以前的时间
            String oldTimeTemp = codeObj.toString().split(":")[1];
            //转化为long类型
            long oldTime = Long.parseLong(oldTimeTemp);
            //获取当前时间戳
            long nowTime = System.currentTimeMillis();
            //设置发送短信的重复发送需要超过一分钟
            if ((nowTime - oldTime) < 1 * 60 * 1000) {
                //放置用户刷新页面，抛繁忙异常
                throw new BusinessException("操作频繁，请稍后再试");
            } else {
                //如果曹操过了一分钟，就获取到之前的验证码，重新发送一次
                smsCode = codeObj.toString().split(":")[0];
            }
        }
        // 将验证码保存到redis中
        redisTemplate.opsForValue().set("register" + phone,smsCode+":"+ System.currentTimeMillis(), 3, TimeUnit.MINUTES);
        System.out.println("您的验证码为"+smsCode);
    }
}
